﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    metaEnum=QMetaEnum::fromType<ResType::TYPE>();
    loadLocation();
    updateView();
    createMenu();
}

Widget::~Widget()
{
    saveLocation();
    saveOrder();
    delete ui;
}

void Widget::generateMenu()
{
    menu->clear();
    if(ui->tabWidget->tabsClosable())
        menu->addAction(QStringLiteral("选项卡禁止关闭"),this,&Widget::tabSwitch);
    else
        menu->addAction(QStringLiteral("选项卡允许关闭"),this,&Widget::tabSwitch);
    menu->addSeparator();
    menu->addAction(QStringLiteral("重置选项卡"),this,&Widget::resetTab);
}

void Widget::tabSwitch()
{
    ui->tabWidget->tabsClosable() ?
                ui->tabWidget->setTabsClosable(false):
                ui->tabWidget->setTabsClosable(true);
    generateMenu();
}

void Widget::updateView()
{
    QStringList order=loadOrder();
    foreach (QString label, order) {
        addTab(label);
    }
}

void Widget::addTab(const QString &label)
{
    std::string key=label.toStdString();
    int value=metaEnum.keyToValue(key.c_str());
    ui->tabWidget->addTab(new TabItem(this,(ResType::TYPE)value),label);
}

void Widget::resetTab()
{
    if(ui->tabWidget->count() > 0)
        ui->tabWidget->clear();

    foreach (QString label, ResType::types()) {
        addTab(label);
    }
}

void Widget::saveOrder()
{
    QStringList order;
    if(ui->tabWidget->count() > 0)
    {
        for(int i=0 ; i < ui->tabWidget->count() ; i++)
            order.append(ui->tabWidget->tabText(i));
    }
    else
        order=ResType::types();

    QSettings cfg(configFile,QSettings::IniFormat);
    cfg.setIniCodec("UTF-8");
    cfg.setValue("Main/tabs",order.join(":"));
}

QStringList Widget::loadOrder()
{
    if(QFile::exists(configFile))
    {
        QSettings cfg(configFile,QSettings::IniFormat);
        cfg.setIniCodec("UTF-8");
        QString tabs=cfg.value("Main/tabs").toString();
        QStringList order=tabs.split(":");
        if(order.isEmpty())
            order=ResType::types();
        return order;
    }
    else
    {
        return ResType::types();
    }
}

void Widget::on_tabWidget_tabCloseRequested(int index)
{
    ui->tabWidget->removeTab(index);
}
